#!/usr/bin/perl

# Xumerle Luciano <luciano.xumerle@gmail.com>
#
# Copyright (c) 2012 Xumerle Luciano. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
#

use strict;
use warnings;

###########################
### MANAGE PARAMETER HERE #
###########################
my %cmd = (
    cpu      => 3,
    samtools => '/usr/bin/samtools',
    java     => '/usr/bin/java',
    gatk     => '/proj/genome/zamo_sequences/gatk/dist/GenomeAnalysisTK.jar',
    varscan  => '/proj/genome/zamo_sequences/VarScan.v2.2.8.jar',
    ref      => '/proj/genome/zamo_sequences/human_g1k_v37.fa',
    gtf      => '/proj/genome/zamo_sequences/Homo_sapiens.GRCh37.65.gtf',
    snps =>
      '/proj/genome/zamo_sequences/dbsnp_132.b37.excluding_sites_after_129.vcf',
);

#########################
### NO CHANGE FROM HERE #
#########################
my $VERSION   = '0.3';
my $COPYRIGHT = '2012-2013';
my $DATE      = '8 feb 2013';

if ( $#ARGV < 0 )
{
    my $n = $0;
    $n =~ s/.pl$//;
    $n =~ s/^.+\///;
    print STDERR qq|$n version $VERSION - $DATE
Copyright (C) $COPYRIGHT Luciano Xumerle
|;
    print STDERR qq|
SYNTAX:

 > $n [-varscan] <file1.bam> <file2.bam> ...

   -varscan : use varscan to detect SNPs.
              UnifiedGenotyper is the default.

DEFAULT OPTIONS (path & settings):
|;
    foreach my $k ( keys %cmd )
    {
        print join( " => ", $k, $cmd{$k} ), "\n";
    }
    print qq|\n=== User can change options editing the scripts ===\n
IMPORT TO DATABASE:
 > $n -pileup <file1> <file2> ...
 > $n -gtf
 > $n -snps
 > $n -vep <output.vep>
 > $n -cosmic <cosmic.tsv>

 > $n -filter [-createtemptable]

--- CONFIG FILE: named "config_bwa2snps" ---

Config file must be in assays directory
>>start example
cpu		3
samtools	/usr/bin/samtools
java		/usr/bin/java
gatk		/backup/ciano/zamo_sequences/gatk/dist/GenomeAnalysisTK.jar
varscan		/backup/ciano/zamo_sequences/VarScan.v2.2.8.jar
ref		/backup/ciano/Homo_sapiens.GRCh37.67/human_g1k_v37.fa
gtf		/backup/ciano/zamo_sequences/Homo_sapiens.GRCh37.65.gtf
snps		/backup/ciano/Homo_sapiens.GRCh37.67/dbsnp_132.b37.excluding_sites_after_129.vcf
<<end example
|;
    exit(0);
}

#
# READ CONFIF FILE
#
open( FILE, 'config_bwa2snps' )
  || die "You must create the \"config_bwa2snps\" file\n\n";
while (<FILE>)
{
    chomp;
    s/^\s*//;
    s/\s*$//;
    my @a = split /\s+/;
    $cmd{ $a[0] } = $a[1];
}
close FILE;

#
# PARSE PARAMETERS
#
if ( defined $ARGV[1] && $ARGV[0] eq '-pileup' )
{
    my @ll = @ARGV;
    shift @ll;
    &pileup2sqlite( \@ll );
    exit(0);
}

if ( $ARGV[0] eq '-gtf' )
{
    &gtf2sqlite();
    exit(0);
}

if ( $ARGV[0] eq '-snps' )
{
    &snps2sqlite();
    exit(0);
}

if ( defined $ARGV[1] && $ARGV[0] eq '-vep' )
{
    &vep2sqlite( $ARGV[1] );
    exit(0);
}

if ( defined $ARGV[1] && $ARGV[0] eq '-cosmic' )
{
    &cosmic2sqlite( $ARGV[1] );
    exit(0);
}

if ( defined $ARGV[0] && $ARGV[0] eq '-filter' )
{
    my $pp = 0;
    $pp++
      if ( defined $ARGV[1] && $ARGV[1] eq '-createtemptable' );
    &filterData($pp);
    exit(0);
}

if ( $ARGV[$#ARGV] !~ m/.bam$/i )
{
    system($0);
    exit(0);
}

my $varscan = 0;
foreach my $bam (@ARGV)
{
    if ( '-varscan' eq $bam )
    {
        $varscan = 1;
        next;
    }

    my $root = '';
    if ( $bam =~ m/^(.+).bam/ )
    {
        $root = $1;
    }

    if ( !-f $bam . '.bai' )
    {
        system( $cmd{samtools}, 'index', $bam, $bam . '.bai' );
    }

    ## rmdup
    system( $cmd{samtools}, 'rmdup', $bam, $root . '-rmdup.bam' );
    system( $cmd{samtools}, 'index',
        $root . '-rmdup.bam',
        $root . '-rmdup.bam.bai'
    );

    ##  RealignerTargetCreator
    system( $cmd{java}, '-Xmx3g', '-jar',
        $cmd{gatk},               '-I',      $root . '-rmdup.bam',
        '-R',                     $cmd{ref}, '-T',
        'RealignerTargetCreator', '-o',      $root . '.intervals',
        '--known',                $cmd{snps}
    );

    ## IndelRealigner
    system( $cmd{java}, '-Xmx6g',
        '-Djava.io.tmpdir=/tmp', '-jar',
        $cmd{gatk},              '-I',
        $root . '-rmdup.bam',    '-R',
        $cmd{ref},               '-T',
        'IndelRealigner',        '-targetIntervals',
        $root . '.intervals',    '-o',
        $root . '.realign.bam',  '--consensusDeterminationModel',
        'KNOWNS_ONLY',           '--knownAlleles',
        $cmd{snps},              '-LOD',
        '0.4'
    );

    system( $cmd{samtools}, 'index',
        $root . '.realign.bam',
        $root . '.realign.bam.bai'
    );

    ## CountCovariates
    system( $cmd{java}, '-Xmx6g', '-Djava.io.tmpdir=/tmp',
        '-jar',            $cmd{gatk},              '-R',
        $cmd{ref},         '-knownSites',           $cmd{snps},
        '-I',              $root . '.realign.bam',  '-T',
        'CountCovariates', '-cov',                  'ReadGroupCovariate',
        '-cov',            'QualityScoreCovariate', '-cov',
        'CycleCovariate',  '-cov',                  'DinucCovariate',
        '-recalFile',      $root . 'recal_data.csv'
    );

    ## TableRecalibration
    system( $cmd{java}, '-Xmx6g', '-jar',
        $cmd{gatk},           '-R',                   $cmd{ref},
        '-I',                 $root . '.realign.bam', '-T',
        'TableRecalibration', '-o',                   $root . '.recal.bam',
        '-recalFile',         $root . 'recal_data.csv'
    );

    system( $cmd{samtools}, 'index',
        $root . '.recal.bam',
        $root . '.recal.bam.bai'
    );

    if ( $varscan == 1 )
    {
        ### VARSCAN SNPS
`$cmd{samtools} mpileup -f $cmd{ref} $root.recal.bam | java -Xmx2g -jar $cmd{varscan} pileup2snp --p-value 0.9 > $root.pileup2snp`;

        ### VARSCAN INDELS
`$cmd{samtools} mpileup -f $cmd{ref} $root.recal.bam | java -Xmx2g -jar $cmd{varscan} pileup2indel --p-value 0.9 > $root.pileup2indel`;
    }
    else
    {
        ### UnifiedGenotyper
        system( $cmd{java}, '-jar', $cmd{gatk},
            '-l',                'INFO',               '-R',
            $cmd{ref},           '-T',                 'UnifiedGenotyper',
            '-I',                $root . '.recal.bam', '-o',
            $root . '.snps.vcf', '--output_mode',      'EMIT_ALL_SITES',
            '-nt',               $cmd{cpu}
        );
    }
}

#############################################
### IMPORT SAMTOOLS RESULTS INTO DATABASE ###
#############################################

sub pileup2sqlite
{
    my @file = @{ (shift) };
    use DBI;
    my $dbargs = {
        AutoCommit => 0,
        PrintError => 1
    };
    my $dbh = DBI->connect( "dbi:SQLite:dbname=demo.db", "", "", $dbargs );
    my $counter = 0;

    ## CREATE TABLE & IMPORT PILEUP FILES
    my $sql = q|CREATE TABLE bwa ( assay text, chrom text, position int,
          ref text, cons text, reads1 text, reads2 text, varfreq text,
          strands1 text, strands2 text, qual1 text, qual2 text,
          pvalue text, mapqual1 text, mapqual2 text,
          reads1plus text, reads1minus text, reads2plus text,
          reads2minus text, varallele text);|;
    $dbh->do($sql);

    my $sth = $dbh->prepare(
        'INSERT INTO bwa VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);');
    foreach my $file (@file)
    {
        my $assay = $file;
        $assay =~ s/.pileup2\w+$//;
        open( FILE, $file ) || die;
        while (<FILE>)
        {
            chomp;
            next if (m/^Chrom\s+Position/);
            my @a = split /\t/;
            $sth->execute( $assay, @a );
            $counter++;
            if ( $counter == 300 )
            {
                $counter = 0;
                $dbh->commit;
            }
        }
        close FILE;
    }
    ### create table's index
    $dbh->do("CREATE INDEX bwacp on bwa (chrom, position);");
    $dbh->commit;
    $dbh->disconnect();
}

sub snps2sqlite
{
    use DBI;
    my $dbargs = {
        AutoCommit => 0,
        PrintError => 1
    };
    my $dbh = DBI->connect( "dbi:SQLite:dbname=demo.db", "", "", $dbargs );
    my $counter = 0;

    ## CREATE TABLE && IMPORT VCF
    my $sql = qq|CREATE TABLE vcf
               (chrom text, pos int, rscode text,
               ref text, alt text, qual text,
               filter text, type text, dbsnpbuildid text);|;
    $dbh->do($sql);

    my $sth = $dbh->prepare('INSERT INTO vcf VALUES(?,?,?,?,?,?,?,?,?);');
    open( FILE, $cmd{snps} ) || die;
    while (<FILE>)
    {
        chomp;
        next if (m/^#/);
        my @a = split "\t";
        my @b = split ';', $a[$#a];
        pop @a;
        my $type         = '';
        my $dbSNPBuildID = '';
        foreach my $ft (@b)
        {
            $type         = $1 if ( $ft =~ m/^VC=(.+)$/i );
            $dbSNPBuildID = $1 if ( $ft =~ m/^dbSNPBuildID=(.+)$/i );
        }
        $sth->execute( @a, $type, $dbSNPBuildID );
        $counter++;
        if ( $counter == 300 )
        {
            $counter = 0;
            $dbh->commit;
        }
    }
    close FILE;
    $dbh->commit;
    $dbh->do("CREATE INDEX vcfcp on vcf (chrom, pos);");
    $dbh->do("CREATE INDEX vcfid ON vcf (rscode);");
    $dbh->commit;
    $dbh->disconnect();
}

sub gtf2sqlite
{
    use DBI;
    my $dbargs = {
        AutoCommit => 0,
        PrintError => 1
    };
    my $dbh = DBI->connect( "dbi:SQLite:dbname=demo.db", "", "", $dbargs );
    my $counter = 0;

    ## CREATE TABLE && IMPORT GTF
    my $sql =
qq|CREATE TABLE gtf (chrom text, function text, type text, start int, stop int,
               strand text, gene_id text, transcript_id text, exon_number int,
               gene_name text, gene_biotype text, transcript_name text);|;
    $dbh->do($sql);

    my $sth = $dbh->prepare('INSERT INTO gtf VALUES(?,?,?,?,?,?,?,?,?,?,?,?);');

    open( FILE, $cmd{gtf} ) || die "FILE " . $cmd{gtf} . " NOT FOUND!!!\n\n";
    while (<FILE>)
    {
        chomp;
        next if (m/^#/);
        my @a               = split "\t";
        my @b               = split '"', $a[$#a];
        my $gene_id         = '';
        my $transcript_id   = '';
        my $exon_number     = '';
        my $gene_name       = '';
        my $gene_biotype    = '';
        my $transcript_name = '';
        for ( my $i = 0 ; $i <= $#b ; $i++ )
        {
            if ( $b[$i] =~ m/gene_id/ ) { $gene_id = $b[ $i + 1 ]; }
            elsif ( $b[$i] =~ m/transcript_id/ )
            {
                $transcript_id = $b[ $i + 1 ];
            }
            elsif ( $b[$i] =~ m/exon_number/ ) { $exon_number = $b[ $i + 1 ]; }
            elsif ( $b[$i] =~ m/gene_name/ )   { $gene_name   = $b[ $i + 1 ]; }
            elsif ( $b[$i] =~ m/gene_biotype/ )
            {
                $gene_biotype = $b[ $i + 1 ];
            }
            elsif ( $b[$i] =~ m/transcript_name/ )
            {
                $transcript_name = $b[ $i + 1 ];
            }
        }
        $sth->execute( @a[ 0, 1, 2, 3, 4, 6 ],
            $gene_id, $transcript_id, $exon_number, $gene_name, $gene_biotype,
            $transcript_name );
        $counter++;
        if ( $counter == 300 )
        {
            $counter = 0;
            $dbh->commit;
        }
    }
    close FILE;
    $dbh->commit;
    $dbh->do("CREATE INDEX gtfid ON gtf (chrom,start,stop);");
    $dbh->commit;
    $dbh->disconnect();
}

sub cosmic2sqlite
{
    my $file = shift;
    use DBI;
    my $dbargs = {
        AutoCommit => 0,
        PrintError => 1
    };
    my $dbh = DBI->connect( "dbi:SQLite:dbname=demo.db", "", "", $dbargs );
    my $counter = 0;

    ## create table
    my $sql = qq|CREATE TABLE cosmic (name text, site text, subtype text,
       histology text, histologysub text, gene text, hgnc_id text,
       mutation_id text, mutation_cds text, mutation_aa, chrom text,
       start int, stop int, pubmed_pmid text )|;
    $dbh->do($sql);

    my $sth =
      $dbh->prepare('INSERT INTO cosmic VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?);');

    open( FILE, $file ) || die "FILE " . $file . " NOT FOUND!!!\n\n";

    while (<FILE>)
    {
        chomp;
        next if ( m/^Sample/ || m/^\s*$/ );
        s/^\s+//;
        s/\s+$//;
        my @a = split "\t", $_ . "\t.";

        foreach my $el (@a) { $el = '' if ( !defined $el || $el =~ m/^\s+$/ ); }

        if ( $#a == 13 && defined $a[11] && $a[11] =~ m/^(.+):(\d+)-(\d+)/ )
        {
            $a[$#a]       = $a[ $#a - 1 ];
            $a[ $#a - 1 ] = $3;
            $a[ $#a - 2 ] = $2;
            $a[ $#a - 3 ] = $1;

            $sth->execute(@a);
            $counter++;
            if ( $counter == 300 )
            {
                $counter = 0;
                $dbh->commit;
            }
        }
    }
    $dbh->do("CREATE INDEX cosmicid ON cosmic (chrom, start, stop);");
    $dbh->do("CREATE INDEX cosmicid2 ON cosmic (chrom, start);");
    $dbh->commit;
    $dbh->disconnect();
}

sub vep2sqlite
{
    my $file = shift;
    use DBI;
    my $dbargs = {
        AutoCommit => 0,
        PrintError => 1
    };
    my $dbh = DBI->connect( "dbi:SQLite:dbname=demo.db", "", "", $dbargs );
    my $counter = 0;

    ## vep output fields
    # uploaded_variation  location  allele  gene  feature  feature_type
    # consequence  cdna_position  cds_position  protein_position  amino_acids
    # codons  existing_variation  extra
    my $sql = qq|CREATE TABLE vep ( chrom text, position int, alleles text,
               gene text, feature text, feature_type text, vep text,
               sift text, polyphen text, condel text,
               cdna_position text, cds_position text, protein_position text,
               amino_acids text, codons text, existing_variation text, extra text );|;
    $dbh->do($sql);

    my $sth = $dbh->prepare(
        'INSERT INTO vep VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);');

    open( FILE, $file ) || die "FILE " . $file . " NOT FOUND!!!\n\n";

    my @damage = (
        'deleterious',           'probably_damaging',
        'possibly_damaging',     '3PRIME_UTR',
        '5PRIME_UTR',            'ESSENTIAL_SPLICE_SITE',
        'NON_SYNONYMOUS_CODING', 'PARTIAL_CODON',
        'REGULATORY_REGION',     'SPLICE_SITE',
        'STOP_GAINED',           'STOP_LOST'
    );

    my @old      = ();
    my @vep      = ();
    my @sift     = ();
    my @polyphen = ();
    my @condel   = ();

    while (<FILE>)
    {
        chomp;
        next if (m/^#/);
        my @a = split /\t/;

        if ( $#old >= 0 && $old[0]->[0] ne $a[0] )
        {
            my $row =
              &create_row( \@old, &uni(@vep), &uni(@sift), &uni(@polyphen),
                &uni(@condel) );
            $sth->execute( @{$row} ) if ( defined $row );

            @old      = ();
            @vep      = ();
            @sift     = ();
            @polyphen = ();
            @condel   = ();
        }

        # prepare damage lists
        $a[13] = '' if ( !defined $a[13] );
        my @b = split ';', $a[13];

        foreach my $d (@b)
        {
            if ( $d =~ m/sift=(.+)\(/i )
            {
                push @sift, uc($1) if ( $1 ~~ @damage );
            }
            elsif ( $d =~ m/polyphen=(.+)\(/i )
            {
                push @polyphen, uc($1) if ( $1 ~~ @damage );
            }
            elsif ( $d =~ m/condel=(.+)\(/i )
            {
                push @condel, uc($1) if ( $1 ~~ @damage );
            }
        }

        my @vvv = split ',', $a[6];
        foreach my $dd (@vvv)
        {
            push @vep, uc($dd) if ( $dd ~~ @damage );
        }
        ## new list
        push @old, \@a;

        $counter++;
        if ( $counter == 300 )
        {
            $counter = 0;
            $dbh->commit;
        }
    }
    close FILE;
    if ( $#old >= 0 )
    {
        my $row =
          &create_row( \@old, &uni(@vep), &uni(@sift), &uni(@polyphen),
            &uni(@condel) );
        $sth->execute(@$row) if ( defined $row );
    }
    $dbh->do("CREATE INDEX vepid ON vep (chrom, position);");
    $dbh->commit;
    $dbh->disconnect();

}

sub uni
{
    my $last = '';
    my @res  = ();
    foreach my $a ( sort (@_) )
    {
        next if ( $last eq $a );
        push @res, $a;
        $last = $a;
    }
    return join ',', @res if ( $#res >= 0 );
    return '';
}

sub create_row
{
    my $old      = shift;
    my $vep      = shift;
    my $sift     = shift;
    my $polyphen = shift;
    my $condel   = shift;

    if ( $vep ne '' || $condel ne '' || $sift ne '' || $polyphen ne '' )
    {
        my @a = @{ $old->[0] };

        my @row = split '_', $a[0];
        push @row, @a[ 3, 4, 5 ], $vep, $sift, $polyphen, $condel,
          @a[ 7 .. $#a ];
        return \@row;
    }
    return undef;
}

sub filterData
{
    my $create = shift;
    use DBI;
    my $dbargs = {
        AutoCommit => 0,
        PrintError => 1
    };
    my $dbh = DBI->connect( "dbi:SQLite:dbname=demo.db", "", "", $dbargs );
    my $counter = 0;

    if ( $create == 1 )
    {
        print STDERR qq{EXECUTE COMMAND:

  > cat merge.sql | sqlite3 demo.db

};
    }

    ## print header
    print join "\t",
      (
        "assay",              "chrom",
        "position",           "ref",
        "variation",          "alleles",
        "rscode",             'site',
        'subtype',            'histology',
        'histologysub',       'hgnc_id',
        'pubmed_pmid',        "gene",
        "vep",                "sift",
        "polyphen",           "condel",
        "cdna_position",      "protein_position",
        "amino_acids",        "codons",
        "existing_variation", "gene_name",
        "gene_biotype"
      );
    print "\n";

    my $all = $dbh->selectall_arrayref(
        'SELECT DISTINCT assay, chrom, position,
         ref, varallele, alleles, rscode,
         site, subtype, histology, histologysub, hgnc_id, pubmed_pmid,
         gene, vep, sift, polyphen, condel, cdna_position, protein_position,
         amino_acids, codons, existing_variation, gene_name, gene_biotype
         FROM temp ORDER BY chrom, position, assay, gene_name;'
    );

    ## start selection
    my @cluster  = ();
    my @vep      = ();
    my @sift     = ();
    my @polyphen = ();
    my @condel   = ();
    my @gene     = ();
    my @type     = ();
    my @ids      = ();

    foreach my $row (@$all)
    {
        foreach (@$row) { $_ = '' if ( !defined || m/^\s*$/ ); }

        if ( $#cluster >= 0 && $cluster[0]->[2] ne $row->[2] )
        {
            &printCluster( \@cluster, \@vep, \@sift, \@polyphen, \@condel,
                \@gene, \@type, \@ids );
            @cluster  = ();
            @vep      = ();
            @sift     = ();
            @polyphen = ();
            @condel   = ();
            @gene     = ();
            @type     = ();
            @ids      = ();
        }
        push @cluster, $row;
        push @ids,     $row->[0];

        push @vep, $row->[ 8 + 6 ] if ( &damage( $row->[ 8 + 6 ] ) == 1 );

        push @sift, $row->[ 9 + 6 ]
          if ( &damage( $row->[ 9 + 6 ] ) == 1 );

        push @polyphen, $row->[ 10 + 6 ]
          if ( &damage( $row->[ 10 + 6 ] ) == 1 );

        push @condel, $row->[ 11 + 6 ]
          if ( &damage( $row->[ 11 + 6 ] ) == 1 );

        push @gene, $row->[ 17 + 6 ];

        push @type, $row->[ 18 + 6 ];
    }
    &printCluster( \@cluster, \@vep, \@sift, \@polyphen, \@condel, \@gene,
        \@type, \@ids )
      if ( $#cluster >= 0 );

    $dbh->disconnect();
}

sub printCluster
{
    my $cluster  = shift;
    my $vep      = shift;
    my $sift     = shift;
    my $polyphen = shift;
    my $condel   = shift;
    my $gene     = shift;
    my $type     = shift;
    my $ids      = shift;

    my @new = ();
    push @new, @{ $cluster->[0] };

    $new[0]        = join ',', @{ &uniq($ids) };
    $new[ 8 + 6 ]  = join ',', @{ &uniq($vep) };
    $new[ 9 + 6 ]  = join ',', @{ &uniq($sift) };
    $new[ 10 + 6 ] = join ',', @{ &uniq($polyphen) };
    $new[ 11 + 6 ] = join ',', @{ &uniq($condel) };
    $new[ 17 + 6 ] = join ',', @{ &uniq($gene) };
    $new[ 18 + 6 ] = join ',', @{ &uniq($type) };

    if ( $#{$cluster} > 0 )
    {
        shift @$cluster;
        foreach my $row (@$cluster)
        {
            for ( my $i = 0 ; $i <= $#{$row} ; $i++ )
            {
                $new[$i] = $row->[$i]
                  if ( ( defined $row->[$i] || $row->[$i] ne '' )
                    && ( !defined $new[$i] || $new[$i] eq '' ) );
            }
        }
    }
    if (   'cosmic' ~~ @$ids
        || $new[ 8 + 6 ]  ne ''
        || $new[ 9 + 6 ]  ne ''
        || $new[ 10 + 6 ] ne ''
        || $new[ 11 + 6 ] ne '' )
    {
        print join "\t", @new;
        print "\n";
    }
}

sub uniq
{
    my $list = shift;
    my @res  = ();
    foreach my $l ( sort @$list )
    {
        next if ( !defined $l );
        push @res, $l if ( $#res < 0 || $res[$#res] ne $l );
    }
    return \@res;
}

sub damage
{
    my $val = shift;
    my @vv = split /\s*,\s*/, $val;

    # valori che salto --> non voglio UTR
    # '3PRIME_UTR', '5PRIME_UTR'

    my @damages = (
        'POSSIBLY_DAMAGING',     'PROBABLY_DAMAGING',
        'DELETERIOUS',           'ESSENTIAL_SPLICE_SITE',
        'NON_SYNONYMOUS_CODING', 'PARTIAL_CODON',
        'REGULATORY_REGION',     'SPLICE_SITE',
        'STOP_GAINED',           'STOP_LOST'
    );
    foreach my $d (@damages)
    {
        foreach my $va (@vv)
        {
            return 1 if ( uc($d) eq uc($va) );
        }
    }
    return 0;
}
